package com.bilibili.server.service;

import com.bilibili.server.entity.Comment;
import com.bilibili.server.entity.User;
import com.bilibili.server.entity.Video;
import com.bilibili.server.repository.CommentRepository;
import com.bilibili.server.repository.UserRepository;
import com.bilibili.server.repository.VideoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class CommentService {
    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private VideoRepository videoRepository;

    // 获取视频评论列表（分页）
    public Page<Comment> getVideoComments(Long videoId, int page, int pageSize) {
        Pageable pageable = PageRequest.of(page - 1, pageSize);
        return commentRepository.findByVideoIdAndParentIdIsNullAndStatus(videoId, 1, pageable);
    }

    // 获取子评论列表（分页）
    public Page<Comment> getChildComments(Long videoId, int parentId, int page, int pageSize) {
        Pageable pageable = PageRequest.of(page - 1, pageSize);
        return commentRepository.findByVideoIdAndParentIdAndStatus(videoId, parentId, 1, pageable);
    }

    // 创建评论
    public Comment createComment(Long videoId, Integer parentId, String content, String username) {
        // 获取用户信息
        User user = userRepository.findByUsernameAndStatus(username, 1)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        // 获取视频信息
        Video video = videoRepository.findById(videoId)
                .orElseThrow(() -> new RuntimeException("视频不存在"));

        // 创建评论
        Comment comment = new Comment();
        comment.setUser(user);
        comment.setVideo(video);
        comment.setContent(content);

        // 如果是回复评论，设置父评论
        if (parentId != null && parentId > 0) {
            Optional<Comment> parentComment = commentRepository.findById(parentId);
            if (parentComment.isPresent()) {
                comment.setParent(parentComment.get());
            }
        }

        return commentRepository.save(comment);
    }

    // 删除评论
    public void deleteComment(int commentId, String username) {
        // 获取评论
        Optional<Comment> commentOptional = commentRepository.findById(commentId);
        if (commentOptional.isPresent()) {
            Comment comment = commentOptional.get();
            
            // 检查是否是评论作者或管理员
            User user = userRepository.findByUsernameAndStatus(username, 1)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            if (!comment.getUser().getId().equals(user.getId()) && !user.getRole().equals("admin")) {
                throw new RuntimeException("没有权限删除该评论");
            }

            // 删除评论（逻辑删除）
            comment.setStatus(0);
            commentRepository.save(comment);
        } else {
            throw new RuntimeException("评论不存在");
        }
    }

    // 点赞评论
    public void likeComment(int commentId) {
        Optional<Comment> commentOptional = commentRepository.findById(commentId);
        if (commentOptional.isPresent()) {
            Comment comment = commentOptional.get();
            comment.setLikeCount(comment.getLikeCount() + 1);
            commentRepository.save(comment);
        } else {
            throw new RuntimeException("评论不存在");
        }
    }
}